import React, { Component, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import {
  Card,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Popconfirm,
  Divider,
  Radio,
  Badge
} from 'antd'
import { connect } from 'dva'
import { LZFormItem } from '@/components/LZForm'
import { goToRouter } from '@/utils/utils'
import commonApi from '@/services/common'
import CopyToClipboard from '@/components/CopyToClipboard'
import SpikeService from './services'

const { Option } = Select

const typeMap = {
  TOPIC: '主题专场',
  SPIKE: '秒杀专场',
  DIRECT: '直购专场'
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

@connect()
@Form.create()
class SecSkill extends Component {
  state = {
    visible: false, // modal的控制
    title: '', // modal的标题
    imgSrc: '',
    fileList: [],
    pageNumber: 1,
    pageSize: 10,
    currentInfo: {},
    loading: true,
    addTabConfirmLoading: false,
    channelData: [],
    tableData: []
  }

  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      render: text => <CopyToClipboard text={text} />
    },
    {
      title: '专场类型',
      dataIndex: 'type',
      align: 'center',
      render: text => typeMap[text]
    },
    {
      title: '专场名称',
      dataIndex: 'title',
      align: 'center',
      width: 100,
      ellipsis: true
    },
    {
      title: '背景色',
      dataIndex: 'backgroundColor',
      align: 'center',
      render: text => {
        return <div className="color-box" style={{ background: text }} />
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      key: 'createTime'
    },
    {
      title: '排序',
      dataIndex: 'sort',
      align: 'center',
      key: 'sort',
      width: 60
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      render: text => {
        const success = text === 'VALID'
        const status = success ? 'success' : 'default'
        const badgeText = success ? '有效' : '无效'
        return <Badge status={status} text={badgeText} />
      }
    },

    {
      title: '操作',
      align: 'center',
      key: 'action',
      width: 200,
      render: (text, record) => (
        <div className="table-action">
          <a onClick={() => this.edit(record)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.detail(record)}>配置详情</a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => this.deleteItem(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ]

  componentDidMount() {
    this.getData()
    this.getChannel()
  }

  getData = () => {
    const { pageNumber, pageSize } = this.state
    this.setState({
      loading: true
    })
    SpikeService.querySpecialIndexPage({
      pageNumber,
      pageSize
    })
      .then(res => {
        this.setState({
          tableData: res.records || [],
          total: res.total,
          current: res.current
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  deleteItem = record => {
    this.setState({
      loading: true
    })
    SpikeService.deleteSpecialIndex({
      id: record.id
    })
      .then(res => {
        this.getData()
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res
      })
    })
  }

  // 新增
  addSpecial = () => {
    this.setState({
      visible: true,
      title: '添加专场'
    })
  }

  detail = row => {
    if (row.type === 'DIRECT') {
      goToRouter(
        this.props.dispatch,
        `/configure/spike/TopicDetailCopy/${row.id}`
      )
    } else {
      const path = row.type === 'SPIKE' ? 'spike' : 'topic'
      goToRouter(
        this.props.dispatch,
        `/configure/spike/${path}Detail/${row.id}`
      )
    }
  }

  edit = record => {
    this.setState({
      visible: true,
      title: '修改专场',
      currentInfo: record,
      fileList: [{ uid: record.id, url: record.imgSrc }]
    })
  }

  // modal的确认
  handleOk = () => {
    this.props.form.validateFields((err, value) => {
      if (!err) {
        this.setState({
          addTabConfirmLoading: true
        })
        const isAdd = this.state.title === '添加专场'
        const service = isAdd
          ? SpikeService.addSpecialIndex
          : SpikeService.modifySpecialIndex
        service({
          ...value,
          channel: value.channel.join('&'),
          id: this.state.currentInfo.id
        })
          .then(res => {
            this.setState(
              {
                visible: false,
                addTabConfirmLoading: false
              },
              () => {
                this.props.form.resetFields()
                this.getData()
              }
            )
          })
          .finally(() => {
            this.setState({
              addTabConfirmLoading: false
            })
          })
      }
    })
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }

  // 上传后删除的回调
  onRemove = () => {
    this.setState({
      fileList: [],
      imgSrc: ''
    })
  }

  // 分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber
      },
      () => {
        this.getData()
      }
    )
  }

  showTotal = () => {
    return `共有${this.state.total}条`
  }

  // 切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize,
        pageNumber: 1
      },
      () => {
        this.getData()
      }
    )
  }

  render() {
    const {
      loading,
      visible,
      addTabConfirmLoading,
      title,
      imgSrc,
      current,
      total,
      currentInfo,
      tableData,
      channelData = []
    } = this.state
    const {
      sort,
      type = 'SPIKE',
      channel,
      title: specialTitle,
      backgroundColor,
      status = 'VALID'
    } = currentInfo
    const { getFieldDecorator } = this.props.form
    const channelIds = (channel && channel.split('&')) || []

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Button type="primary" className="mb-18" onClick={this.addSpecial}>
            添加专场
          </Button>
          <Table
            loading={loading}
            columns={this.columns}
            dataSource={tableData}
            rowKey={record => record.id}
            pagination={{
              current,
              total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange
            }}
          />
        </Card>
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={addTabConfirmLoading}
          destroyOnClose
          onCancel={() => {
            this.setState({
              visible: false,
              currentInfo: {},
              fileList: [],
              imgSrc: []
            })
          }}
        >
          <Form {...formItemLayout}>
            <LZFormItem
              field="type"
              label="专场类型"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="专场类型不能为空"
              initialValue={type}
            >
              <Select placeholder="请选择">
                <Option value="SPIKE" key="SPIKE">
                  秒杀专场
                </Option>
                <Option value="TOPIC" key="TOPIC">
                  主题专场
                </Option>
                <Option value="DIRECT" key="DIRECT">
                  直购专场
                </Option>
              </Select>
            </LZFormItem>
            <LZFormItem
              field="channel"
              label="上架渠道"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="上架渠道不能为空"
              initialValue={channelIds}
            >
              <Select placeholder="请选择" mode="multiple">
                {channelData.map(item => (
                  <Option key={item.appId} value={item.channelId}>
                    {item.channelName}
                  </Option>
                ))}
              </Select>
            </LZFormItem>
            <LZFormItem
              field="title"
              label="专场标题"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="专场标题不能为空"
              initialValue={specialTitle}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="backgroundColor"
              label="背景色"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="背景色不能为空"
              initialValue={backgroundColor}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="sort"
              label="排序"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="排序不能为空"
              initialValue={sort}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              label="状态"
              field="status"
              required
              getFieldDecorator={getFieldDecorator}
              initialValue={status}
            >
              <Radio.Group>
                <Radio value="VALID">有效</Radio>
                <Radio value="INVALID">无效</Radio>
              </Radio.Group>
            </LZFormItem>
          </Form>
        </Modal>
        <Modal
          title="图片预览"
          visible={this.state.imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={imgSrc || currentInfo.imgSrc}
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default SecSkill
